import { createEventHook } from '@vueuse/core'

export function useUpload(url: string, file: File, method = 'PUT') {
  const progress = createEventHook<number>()
  const success = createEventHook<Response>()
  const error = createEventHook<Response>()

  const reader = file.stream().getReader()
  const totalSize = file.size
  let uploadedSize = 0
  const abortController = new AbortController()

  fetch(url, { method, body: file, signal: abortController.signal })
    .then((response) => {
      if (!response.ok) {
        error.trigger(response)
      } else {
        success.trigger(response)
      }
    })
    .catch((e) => error.trigger(e))

  reader.read().then(function processChunk({ done, value }) {
    if (done) {
      return
    }

    uploadedSize += value.length
    progress.trigger(uploadedSize / totalSize)

    reader.read().then(processChunk)
  })

  return {
    onProgress: progress.on,
    onSuccess: success.on,
    onError: error.on,
    abort: () => abortController.abort()
  }
}
